extends Node

var db: SQLite             = SQLite.new()
const verbosity_level: int = SQLite.VERBOSE
# db 文件存储的位置
var db_name  := "res://system/db/data/"
var tab_name := "table_name"


func _ready():
	init_db()


# 初始化db
func init_db():
	db.path = db_name
	db.verbosity_level = verbosity_level
	# 使用在path变量中找到的db_name打开数据库
	db.open_db()
	pass


# 创建表
func create_table(fig: table_fig):
	# Create a table with the structure found in table_dict and add it to the database
	print(fig.get_table_name())
	db.create_table(fig.get_table_name(), fig.get_table_dict())


# 根据对象创建表
func create_table_obj(model: Object):
	var tab_fig: table_fig = get_mode_property(model)
	create_table(tab_fig)


# 根据对象创建表 自定义表名
func create_table_name(table_name: String, model: Object):
	var tab_fig: table_fig = get_mode_property(model)
	tab_fig.set_table_name(table_name)
	create_table(tab_fig)


# 查询所有字段
func select_all(table_name: StringName, sql: String) ->Array:
	# Select the employee with the name Olga and with age 30
	var selected_array: Array = db.select_rows(table_name, sql, ["*"])
	return selected_array


# 原生sql查询
func query(sql: String):
	# Do a normal query
	# db.query("SELECT COUNT(*) AS 'number_of_employees' FROM " + table_name + ";")
	db.query(sql)
	return db.query_result


# 新增数据
func insert(table_name: StringName, row_dict: Dictionary):
	db.insert_row(table_name, row_dict)


#  修改数据
func update(table_name: StringName, condition: String, row_dict: Dictionary):
	# 修改 name = Amanda 的数据，吧 age修改为 30 name修改为 Olga
	# db.update_rows(table_name, "name = 'Amanda'", {"AGE":30, "NAME":"Olga"})
	db.update_rows(table_name, condition, row_dict)


# 删除数据
func delete(table_name: StringName, condition: String):
	#删除名为Olga的员工
	#db.delete_rows(table_name, "name = 'Olga'")
	db.delete_rows(table_name, condition)


# 清空数据
func delete_table_all_data(table_name: StringName):
	var sql := "DELETE FROM %s;" % [table_name]
	query(sql)


# 构建创建表对象
func get_mode_property(model:Object) -> table_fig:
	var pros :Array = model.get_property_list()
	var tab_fig: table_fig = table_fig.new()
	var pros_dic :Dictionary =  Dictionary()
	print(pros)
	for pro in pros:
		match pro["type"]:
			Variant.Type.TYPE_INT:
				if pro["name"] == "id":
					pros_dic[pro["name"]] = {"data_type":"int", "primary_key": true, "not_null": true}
				else:
					pros_dic[pro["name"]] = {"data_type":"int", "not_null": true}
			Variant.Type.TYPE_FLOAT:
				pros_dic[pro["name"]] = {"data_type":"real"}
			Variant.Type.TYPE_STRING:
				pros_dic[pro["name"]] = {"data_type":"text", "not_null": true}
			Variant.Type.TYPE_STRING_NAME:
				pros_dic[pro["name"]] = {"data_type":"text", "not_null": true}
			_ :
				pass
	tab_fig.set_table_dict(pros_dic)
	return tab_fig


